package com.common.util.sevenz.controller;

import com.common.util.sevenz.SevenZipUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author
 * @Describe 功能描述
 * @date
 */
@RestController
public class SevenzTestController {

    String srcPath = "C:\\Users\\fujw27320\\Desktop\\7zTest";
    String dest7zFilePath = "C:\\Users\\fujw27320\\Desktop\\7zTest.7z";

    String destPath = "C:\\Users\\fujw27320\\Desktop\\un7z";

    @RequestMapping(value = "compress7z")
    public void compress7z(HttpServletResponse response, String type) throws IOException {
        if (StringUtils.isEmpty(type)) {
            // 浏览器响应
            // 浏览器响应返回
            response.reset();
            // 设置response的header，response为HttpServletResponse接收输出流
            response.setContentType("application/octet-stream");
            String sevenzFileName = "7zFile-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern(
                    "yyyyMMddHHmmss")) + ".7z";
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(sevenzFileName, "UTF-8"));

            // 压缩为7z
            SevenZipUtil.compress7z(srcPath, dest7zFilePath);
            // 将压缩好的7z响应给浏览器
            File file = new File(dest7zFilePath);
            if (null != file && file.isFile()) {
                ServletOutputStream os = response.getOutputStream();
                FileInputStream fis = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);
                int len = -1;
                // 将源文件写入到输出流
                byte[] buf = new byte[1024];
                while ((len = bis.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }

                bis.close();
                fis.close();
                os.close();
            }
        } else {
            // 写到目标文件
            SevenZipUtil.compress7z(srcPath, dest7zFilePath);
        }
    }

    @RequestMapping(value = "unCompress7z")
    public void unCompress7z() throws Exception {
        // 解压
        SevenZipUtil.unCompress7z(dest7zFilePath, destPath);
    }
}
